<route lang="json">
{
    "name": "orderManage",
    "meta": {
        "title": "控制台-订单管理",
        "requiresAuth": true
    }
}
</route>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { getOrderList, getOrderStatusList, updateOrderStatus } from '~/api/order'

// 定义订单接口类型
interface Order {
  orderid: string // 订单ID
  userid: string // 用户ID
  status: number // 订单状态
  proname: string // 商品名称
  proid: string // 商品ID
  originprice: number // 原价
  discount: number // 折扣
  num: number // 数量
  img1: string // 商品图片
  time: string // 订单时间
  name?: string // 收货人姓名
  tel?: string // 联系电话
  province?: string // 省份
  city?: string // 城市
  county?: string // 区县
  addressDetail?: string // 详细地址
  [key: string]: any
}

// 订单状态映射
const orderStatusMap: Record<number, { label: string, type: 'warning' | 'info' | 'primary' | 'success' | 'danger' }> = {
  0: { label: '待付款', type: 'warning' },
  1: { label: '待发货', type: 'info' },
  2: { label: '已发货', type: 'primary' },
  3: { label: '已完成', type: 'success' },
  4: { label: '已取消', type: 'danger' },
  5: { label: '已退款', type: 'danger' },
}

// 订单列表数据
const orderList = ref<Order[]>([])
const loading = ref(false)

// 表格分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 搜索条件
const searchForm = reactive({
  orderNo: '',
  username: '',
  status: '',
  startDate: '',
  endDate: '',
})

// 当前选中的订单状态标签
const activeStatus = ref('')

// 获取订单列表
async function fetchOrderList() {
  loading.value = true
  try {
    let res
    if (activeStatus.value !== '') {
      // 获取特定状态的订单
      const status = Number.parseInt(activeStatus.value)
      if (!Number.isNaN(status)) {
        res = await getOrderStatusList(status)
      }
      else {
        // 如果状态不是有效数字，获取所有订单
        res = await getOrderList()
      }
    }
    else {
      // 获取所有订单
      res = await getOrderList()
    }
    console.warn(res)
    if (res && Array.isArray(res)) {
      orderList.value = res
      pagination.total = res.length
    }
    else if (res && typeof res === 'object' && Array.isArray(res.data)) {
      orderList.value = res.data
      pagination.total = res.data.length
    }
    else {
      orderList.value = []
      pagination.total = 0
    }
  }
  catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
    orderList.value = []
    pagination.total = 0
  }
  finally {
    loading.value = false
  }
}

// 处理分页变化
function handleCurrentChange(val: number) {
  pagination.currentPage = val
}

function handleSizeChange(val: number) {
  pagination.pageSize = val
  pagination.currentPage = 1
}

// 搜索
function handleSearch() {
  pagination.currentPage = 1
}

// 重置搜索
function resetSearch() {
  Object.assign(searchForm, {
    orderNo: '',
    username: '',
    status: '',
    startDate: '',
    endDate: '',
  })
  pagination.currentPage = 1
}

// 过滤数据
const filteredData = computed(() => {
  let result = [...orderList.value]

  // 按订单号筛选
  if (searchForm.orderNo) {
    result = result.filter(item => item.orderid.includes(searchForm.orderNo))
  }

  // 按用户名筛选
  if (searchForm.username) {
    result = result.filter(item => item.userid && item.userid.includes(searchForm.username))
  }

  // 按状态筛选
  if (searchForm.status !== '') {
    result = result.filter(item => item.status === Number(searchForm.status))
  }

  // 按日期范围筛选
  if (searchForm.startDate && searchForm.endDate) {
    const start = new Date(searchForm.startDate).getTime()
    const end = new Date(searchForm.endDate).getTime()
    result = result.filter((item) => {
      const createTime = Number(item.time) || 0
      return createTime >= start && createTime <= end
    })
  }

  return result
})

// 计算当前页的数据
const currentPageData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredData.value.slice(start, end)
})

// 更新订单状态
async function updateStatus(orderId: string, status: number) {
  try {
    await updateOrderStatus(orderId, status)
    ElMessage.success('更新订单状态成功')
    fetchOrderList()
  }
  catch (error) {
    console.error('更新订单状态失败:', error)
    ElMessage.error('更新订单状态失败')
  }
}

// 处理发货
function handleShip(row: Order) {
  ElMessageBox.confirm('确定要将订单标记为已发货吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    updateStatus(row.orderid, 2)
  }).catch(() => {})
}

// 处理完成
function handleComplete(row: Order) {
  ElMessageBox.confirm('确定要将订单标记为已完成吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    updateStatus(row.orderid, 3)
  }).catch(() => {})
}

// 处理取消
function handleCancel(row: Order) {
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    updateStatus(row.orderid, 4)
  }).catch(() => {})
}

// 处理退款
function handleRefund(row: Order) {
  ElMessageBox.confirm('确定要将订单标记为已退款吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    updateStatus(row.orderid, 5)
  }).catch(() => {})
}

// 查看订单详情
const detailDialogVisible = ref(false)
const currentOrder = ref<Order | null>(null)

function viewOrderDetail(row: Order) {
  currentOrder.value = row
  detailDialogVisible.value = true
}

// 页面加载时获取订单列表
onMounted(() => {
  fetchOrderList()
})
</script>

<template>
  <div class="order-manage-container">
    <div class="order-header">
      <h2 class="order-title">
        订单管理
      </h2>
    </div>

    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择订单状态" clearable style="width: 120px;">
            <el-option
              v-for="(status, key) in orderStatusMap"
              :key="key"
              :label="status.label"
              :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="searchForm.startDate"
            type="date"
            placeholder="开始日期"
            style="width: 150px"
          />
          <span class="date-separator">至</span>
          <el-date-picker
            v-model="searchForm.endDate"
            type="date"
            placeholder="结束日期"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            搜索
          </el-button>
          <el-button @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card shadow="hover" class="order-card">
      <el-table v-loading="loading" :data="currentPageData" stripe border style="width: 100%">
        <!-- 序号 -->
        <el-table-column type="index" label="序号" />

        <!-- 订单号列 -->
        <el-table-column prop="orderid" label="订单号" min-width="180" show-overflow-tooltip />

        <!-- 用户列 -->
        <el-table-column prop="userid" label="用户ID" min-width="120">
          <template #default="scope">
            {{ scope.row.userid || '-' }}
          </template>
        </el-table-column>

        <!-- 商品名称列 -->
        <el-table-column prop="proname" label="商品名称" min-width="180" show-overflow-tooltip />

        <!-- 金额列 -->
        <el-table-column label="订单金额" width="120">
          <template #default="scope">
            ¥{{ (scope.row.originprice * scope.row.discount / 10 * scope.row.num).toFixed(2) }}
          </template>
        </el-table-column>

        <!-- 状态列 -->
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="orderStatusMap[scope.row.status]?.type || 'info'">
              {{ orderStatusMap[scope.row.status]?.label || '未知状态' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 下单时间列 -->
        <el-table-column label="下单时间" min-width="180">
          <template #default="scope">
            {{ scope.row.time ? new Date(Number(scope.row.time)).toLocaleString() : '-' }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="viewOrderDetail(scope.row)">
              查看详情
            </el-button>
            <template v-if="scope.row.status === 1">
              <el-button type="success" link @click="handleShip(scope.row)">
                发货
              </el-button>
            </template>
            <template v-if="scope.row.status === 2">
              <el-button type="success" link @click="handleComplete(scope.row)">
                完成
              </el-button>
            </template>
            <template v-if="scope.row.status === 0">
              <el-button type="danger" link @click="handleCancel(scope.row)">
                取消
              </el-button>
            </template>
            <template v-if="scope.row.status === 1">
              <el-button type="danger" link @click="handleRefund(scope.row)">
                退款
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="filteredData.length"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="700px" destroy-on-close>
      <template v-if="currentOrder">
        <div class="order-detail">
          <div class="detail-section">
            <h3 class="section-title">
              基本信息
            </h3>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单号">
                {{ currentOrder.orderid }}
              </el-descriptions-item>
              <el-descriptions-item label="用户ID">
                {{ currentOrder.userid || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="订单金额">
                ¥{{ (currentOrder.originprice * currentOrder.discount / 10 * currentOrder.num).toFixed(2) }}
              </el-descriptions-item>
              <el-descriptions-item label="订单状态">
                <el-tag :type="orderStatusMap[currentOrder.status]?.type || 'info'">
                  {{ orderStatusMap[currentOrder.status]?.label || '未知状态' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="下单时间">
                {{ currentOrder.time ? new Date(Number(currentOrder.time)).toLocaleString() : '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="detail-section">
            <h3 class="section-title">
              收货信息
            </h3>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="收货人">
                {{ currentOrder.name || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="联系电话">
                {{ currentOrder.tel || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="收货地址">
                {{ currentOrder.province && currentOrder.city && currentOrder.county
                  ? `${currentOrder.province}${currentOrder.city}${currentOrder.county}${currentOrder.addressDetail || ''}` : '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="detail-section">
            <h3 class="section-title">
              商品信息
            </h3>
            <el-table
              :data="[{
                proname: currentOrder.proname,
                proid: currentOrder.proid,
                price: currentOrder.originprice * currentOrder.discount / 10,
                count: currentOrder.num,
                img: currentOrder.img1,
              }]" border style="width: 100%"
            >
              <el-table-column label="商品图片" width="100">
                <template #default="scope">
                  <el-image
                    v-if="scope.row.img"
                    :src="scope.row.img"
                    preview-teleported
                    :preview-src-list="[scope.row.img]"
                    fit="cover"
                    style="width: 80px; height: 80px"
                  />
                  <div v-else class="no-image">
                    无图片
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="proname" label="商品名称" min-width="150" show-overflow-tooltip />
              <el-table-column label="单价" width="100">
                <template #default="scope">
                  ¥{{ scope.row.price.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column prop="count" label="数量" width="80" />
              <el-table-column label="小计" width="120">
                <template #default="scope">
                  ¥{{ (scope.row.price * scope.row.count).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.order-manage-container {
  padding: 20px;

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .order-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
  }

  .status-card {
    margin-bottom: 20px;
  }

  .search-card {
    margin-bottom: 20px;

    .date-separator {
      margin: 0 5px;
    }
  }

  .order-card {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .order-detail {
    .detail-section {
      margin-bottom: 20px;

      .section-title {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 10px;
        padding-left: 10px;
        border-left: 3px solid #409eff;
      }
    }

    .no-image {
      width: 80px;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f5f7fa;
      color: #909399;
      border: 1px dashed #d9d9d9;
    }
  }
}
</style>
